package com.example.multiple.listener;

import com.example.multiple.config.DynamicDataSource;
import com.example.multiple.config.MyDataSource;
import com.example.multiple.config.MyDataSourceConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.cloud.endpoint.event.RefreshEventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author yanggld
 * @Date 2019/9/27-18:59
 * @Description
 * 自定义刷新事件的监听
 */
@Component
public class CustomRefreshEventListener extends RefreshEventListener {

	private final static String DATASOURCE_PREFIX = "datasource.clients";

	@Autowired
	private MyDataSourceConfig myDataSourceConfig;

	private ContextRefresher refresh;

	public CustomRefreshEventListener(ContextRefresher refresh) {
		super(refresh);
		this.refresh = refresh;
	}

	@Override
	public void handle(RefreshEvent event) {
		Set<String> keys = refresh.refresh();
		if (!CollectionUtils.isEmpty(keys)) {
			for (String key : keys) {
				// 动态增减数据源
				if (key.startsWith(DATASOURCE_PREFIX)) {
					setDs();
					return;
				}
			}
		}
	}

	/**
	 * 动态增减数据源
	 */
	public void setDs(){
		Map<Object, Object> targetDataSource = new HashMap<>();
		List<MyDataSource> myDataSourceList = myDataSourceConfig.getDs();
		for (MyDataSource ds : myDataSourceList) {
			targetDataSource.put(ds.getNickname(), ds);
		}
		DynamicDataSource.getInstance().setTargetDataSources(targetDataSource);
	}

}
